<template>
  <el-card class="box-card defaultTable">
    <el-table v-loading="loading" :data="d.tableData" style="width: 100%">
      <el-table-column prop="nickname" label="名称"> </el-table-column>
      <el-table-column prop="code_key" label="KEY" width="480" />
      <el-table-column prop="code" label="CODE" />
      <el-table-column prop="createtime" label="创建时间" />
      <el-table-column align="right" label="操作">
        <template #default="scope">
          <div class="dflex justify-content-end">
            <div class="base-del" @click="onDel(scope.row.id)">
              <img :src="del" alt="" srcset="" />
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts" setup>
import { APIDelKey, APIGenerateKey, APIKeyList } from "@/api/apiKey"
import { defaultTableType } from "@/api/interface/types/InterfaceTypes"
import del from "@/assets/docs/del.svg"
import debounce from "@/utils/debounce"
import dayjs from "dayjs"
import { ElMessage, ElMessageBox } from "element-plus"
import Pubsub from "pubsub-js"
import { onMounted, reactive, ref } from "vue"

const loading = ref<boolean>(false)
const pid = ref("")

// 初始化
const initModel = async () => {
  loading.value = true
  let params = {
    page: 1
  }
  let { data, code } = await APIKeyList(params)
  if (code !== 200) return

  d.tableData = data.list.map((item: any) => {
    item.createtime = dayjs.unix(item.createtime).format("YYYY-MM-DD HH:mm:ss")
    return item
  })
  loading.value = false
}

onMounted(() => {
  initModel()
  //消息订阅
  pid.value = Pubsub.subscribe("MIDDLEGROUND_KEY", () => generateKey())
})

// 生成中台key
const generateKey = debounce(async () => {
  const { code } = await APIGenerateKey()
  if (code === 200) {
    ElMessage({
      type: "success",
      message: "生成成功"
    })
    initModel()
  } else {
    ElMessage({
      type: "error",
      message: "生成失败"
    })
  }
}, 300)

const d = reactive<defaultTableType>({
  tableData: []
})
const delFn = (p: number) => {
  let newList = d.tableData.filter((e) => e.id !== p)
  d.tableData = newList
}
const onDel = debounce((id: number) => {
  ElMessageBox.confirm("KEY将永久删除，请谨慎操作！是否继续删除？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let { code } = await APIDelKey({ id })
    if (code === 200) {
      delFn(id)
      ElMessage({
        type: "success",
        message: "删除成功"
      })
    }
  })
}, 300)
</script>
<style lang="scss" scoped>
.el-card {
  box-shadow: none;
  border: none;
}
</style>
